package com.pj.project4sp.git;

import com.dtflys.forest.Forest;
import com.pj.utils.sg.AjaxError;
import com.pj.utils.sg.AjaxJson;
import com.pj.utils.sg.IpCheckUtil;
import com.pj.utils.sg.NbUtil;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试controller
 * @author kong
 */
@RestController
public class GitController {

    @Value("${git.clientId}")
    String clientId;

    @Value("${git.clientSecret}")
    String clientSecret;


    /**
     * 测试请求，如果能正常访问此路由，则证明项目已经部署成功
     * @return
     */
    @RequestMapping("/oauth/token")
    public AjaxJson test(String code, String redirect_uri, String client_id, String client_secret) {
        // 防频繁
        IpCheckUtil.checkResToNow("oauth-token", 1);

        // 校验
        AjaxError.throwByIsNull(code, "缺少 code");
        AjaxError.throwByIsNull(redirect_uri, "缺少 redirect_uri");
        AjaxError.throwByIsNull(client_id, "缺少 client_id");
        AjaxError.throwByIsNull(client_secret, "缺少 client_secret");

        // 请求
        String res = Forest.post("https://gitee.com/oauth/token")
                .addBody("grant_type", "authorization_code")
                .addBody("code", code)
                .addBody("client_id", clientId)
                .addBody("client_secret", clientSecret)
                .addBody("redirect_uri", redirect_uri)
                .executeAsResponse()
                .getContent();
//                .executeAsString()
        ;
        System.out.println("http 请求返回：" + res);

        // 转 json
        SoMap so = SoMap.getSoMap().setJsonString(res);

        /*
            // 正确返回：
            {
                "access_token": "03ec6b673d834f54867ce4b8a1851950",
                "token_type": "bearer",
                "expires_in": 86400,
                "refresh_token": "7e9f56a5c30642b744bc3a9f2ca899783c5349208409bf74bf88a302c0d54ac1",
                "scope": "user_info projects",
                "created_at": 1691307911
            }
            // 失败返回：
            {
                "error": "invalid_grant",
                "error_description": "授权方式无效，或者登录回调地址无效、过期或已被撤销"
            }
         */

        // 拿值
        if(so.has("access_token")) {
            return AjaxJson.getSuccess().set("access_token", so.get("access_token"));
        } else {
            return AjaxJson.getError(so.getString("error_description"));
        }
    }

}
